from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from datetime import timedelta
import os
import uuid
from django.conf import settings
from users.services import avatar_upload_path


# 用于存储用户个人信息，视为user模型的扩展字段
class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    luogu_uid = models.CharField(max_length=100, blank=True, null=True)
    avatar = models.ImageField(upload_to=avatar_upload_path, blank=True, null=True)

    # property将类中的方法转换为属性
    @property
    def avatar_url(self):
        if self.avatar:
            return f"{settings.MEDIA_URL}{self.avatar}"
        return f"{settings.STATIC_URL}default_avatar.jpg"  # 默认头像路径
    # 其他可能的自定义字段

    # 参数是user , 返回值是user对应的luogu_uid
    @classmethod
    def get_luogu_uid_by_user(cls, user):
        try:
            # 获取关联的 UserProfile 实例
            user_profile = UserProfile.objects.get(user=user)
            # 返回 luogu_uid
            return user_profile.luogu_uid
        except UserProfile.DoesNotExist:
            # 如果 UserProfile 不存在
            print(f"UserProfile for user {user.username} does not exist.")
            return None
        except Exception as e:
            # 捕获其他潜在异常
            print(f"An error occurred: {str(e)}")
            return None

    # 参数是user_id , 返回值是user_id对应用户的luogu_uid
    @classmethod
    def get_luogu_uid_by_user_id(cls, user_id):
        try:
            # 根据 user_id 获取关联的 User 实例
            user = User.objects.get(id=user_id)
            # 获取关联的 UserProfile 实例
            user_profile = UserProfile.objects.get(user=user)
            # 返回 luogu_uid
            return user_profile.luogu_uid
        except User.DoesNotExist:
            # 如果 User 不存在
            print(f"User with ID {user_id} does not exist.")
            return None
        except UserProfile.DoesNotExist:
            # 如果 UserProfile 不存在
            print(f"UserProfile for user with ID {user_id} does not exist.")
            return None
        except Exception as e:
            # 捕获其他潜在异常
            print(f"An error occurred: {str(e)}")
            return None

    def __str__(self):
        return self.user.username


# 注册用的临时User类
from django.contrib.auth.hashers import make_password, check_password

class PendingUser(models.Model):
    username = models.CharField(max_length=150)
    email = models.EmailField()
    password = models.CharField(max_length=128)  # 存储哈希后的密码
    luogu_uid = models.CharField(max_length=20)
    verification_code = models.CharField(max_length=6)
    created_at = models.DateTimeField(auto_now_add=True)  # 自动设置创建时间
    is_verified = models.BooleanField(default=False)

    def is_expired(self):
        """检查是否超时，假设超时时限为30分钟"""
        return timezone.now() > self.created_at + timedelta(minutes=30)

    def __str__(self):
        return f"PendingUser: {self.username} ({self.email})"

    @staticmethod
    def cleanup_expired():
        """清理所有过期的 PendingUser 记录"""
        expired_users = PendingUser.objects.filter(created_at__lt=timezone.now() - timedelta(minutes=30))
        expired_users.delete()

